﻿#include <glog/logging.h>
#include <QDateTime>
#include <QThread>

#include "constant.h"
#include "entity/mqtt_entity.h"
#include "manager/algorithm_manager.h"
#include "manager/config_manager.h"
#include "manager/datakeeper.h"

using namespace std;
unsigned int number;

AlgorithmManager *AlgorithmManager::get_instance() {
    static AlgorithmManager instance;
    return &instance;
}

AlgorithmManager::AlgorithmManager()
{
    model_file = MODULE_FILE;
    weights_file = WEIGHT_FILE;
    mean_file = MEAN_FILE;
    mean_value = MEAN_VALUE;
    confidence_threshold = 0.3;
    detector_thread = new DetectorThread(model_file, weights_file, mean_file, mean_value);
    connect(this, SIGNAL(sig_detect(QSharedPointer<Mat>)), detector_thread, SLOT(on_detect(QSharedPointer<Mat>)));
    connect(detector_thread, SIGNAL(sig_result(QSharedPointer<Mat>)), this, SLOT(on_result(QSharedPointer<Mat>)));
    connect(detector_thread, SIGNAL(sig_result_detail(QSharedPointer<Mat>,std::vector<ObjectEntity>)),
            this, SLOT(on_result_detail(QSharedPointer<Mat>, std::vector<ObjectEntity>)));
}

AlgorithmManager::~AlgorithmManager() {
    if (detector_thread == NULL) {
        delete detector_thread;
        detector_thread = NULL;
    }
}

bool AlgorithmManager::init() {
    detector_thread->start();
    return true;
}

void AlgorithmManager::detect(QSharedPointer<Mat> sp_frame) {
    emit sig_detect(sp_frame);
}

 void AlgorithmManager::on_result(QSharedPointer<Mat> sp_frame) {
     LOG(INFO) << "AlgorithmManager | on_result";
     AppConfig *ptr_app_config = ConfigManager::getInstance()->get_app_config();
     // 显示图片
     if (ptr_app_config->show_video) {
        cv::imshow("video", *sp_frame);
     }
 }

 void AlgorithmManager::on_result_detail(QSharedPointer<Mat> sp_frame, std::vector<ObjectEntity> objects) {
     LOG(INFO) << "AlgorithmManager | on_result_detail";
     AppConfig *ptr_app_config = ConfigManager::getInstance()->get_app_config();
     // 显示检测结果
     if (ptr_app_config->show_detect) {
        for (std::vector<ObjectEntity>::iterator it = objects.begin(); it != objects.end(); ++it) {
            if (it->found == false) {
                cv::rectangle(*sp_frame, cv::Rect(it->x, it->y, it->width, it->height), cvScalar(0, 0, 255), 2);
                std::ostringstream oss_result;
                oss_result << it->id;
                cv::putText(*sp_frame, oss_result.str(), cvPoint(it->x, it->y), cv::FONT_HERSHEY_COMPLEX_SMALL, 1, cv::Scalar(0, 255, 0), 1);
            } else {
                cv::rectangle(*sp_frame, cv::Rect(it->x, it->y, it->width, it->height), cvScalar(255, 0, 0), 2);
            }
        }
     }
     // 显示图片
     if (ptr_app_config->show_video) {
        cv::imshow("video", *sp_frame);
     }
 }
